﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data;
using System.Text;
using Sinacor.Infra.Service.Data;
using Sinacor.Infra.Service.Common;
using Sinacor.Infra.Service.Security.Authorization;

namespace Sinacor.Servico.Bovespa.Movimento.ResourceAccess
{
    public class ControleMovimentoBolsa : BaseResourceAccess
    {
        #region Construtor

        /// <summary>
        /// Construtor
        /// </summary>
        public ControleMovimentoBolsa() : base(AuthorizationContext.Current.CompanyId) { }

        #endregion

        #region Métodos Públicos

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public BusinessEntity.InformacoesMovimento ObterInformacoesMovimento(BusinessEntity.DataMovimento request)
        {
            BusinessEntity.InformacoesMovimento response = new BusinessEntity.InformacoesMovimento();
            StringBuilder sql = new StringBuilder();

            sql.Append("SELECT ");
            sql.Append("DT_DATMOV AS DataMovimento, ");
            sql.Append("TP_MOVIMENTO AS TipoMovimento ");
            sql.Append("FROM TBOPARAM ");

            //Filtro Opcional
            if (request.Valor.HasValue)
                if (request.Valor.Value != DateTime.MinValue)
                    sql.Append("WHERE DT_DATMOV = :DataMovimento");

            using (DbCommand dbCommand = this.DataBase.GetSqlStringCommand(sql.ToString()))
            {
                #region Adição dos parâmetros

                if (request.Valor.HasValue)
                    if (request.Valor.Value != DateTime.MinValue)
                        this.DataBase.AddInParameter(dbCommand, "DataMovimento", DbType.DateTime, request.Valor);

                #endregion

                #region Execução                

                response = this.FindOne<BusinessEntity.InformacoesMovimento>(dbCommand, 
                    reader => 
                    {
                        BusinessEntity.InformacoesMovimento entity = new BusinessEntity.InformacoesMovimento();
                        entity.DataMovimento = reader.GetValue<DateTime>("DataMovimento");
                        entity.EstadoMovimento = EnumConverter.Parse<BusinessEntity.Enum.TipoMovimento>(reader["TipoMovimento"].ToString());
                        return entity;
                    });               

                #endregion
            }

            return response;
        }

        #endregion        
    }        
}